package com.xzp.yygh.hosp.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.xzp.yygh.cmn.client.DictFeignClient;
import com.xzp.yygh.enums.DictEnum;
import com.xzp.yygh.hosp.repository.HospitalRepository;
import com.xzp.yygh.hosp.service.HospitalService;
import com.xzp.yygh.model.hosp.BookingRule;
import com.xzp.yygh.model.hosp.Hospital;
import com.xzp.yygh.vo.hosp.HospitalQueryVo;
import org.joda.time.DateTime;
import org.joda.time.format.DateTimeFormat;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class HospitalServiceImpl implements HospitalService {

    @Autowired
    private HospitalRepository hospitalRepository;

    @Autowired
    private DictFeignClient dictFeignClient;


    @Override
    public void save(Map<String, Object> paramMap) {
//        log.info(JSONObject.toJSONString(paramMap));
        // 将数据从Map转为Hospital类型   -> 先转string再转hospitalset
        Hospital hospital = JSONObject.parseObject(JSONObject.toJSONString(paramMap),Hospital.class);
        //判断在数据库中是否存在
        Hospital targetHospital = hospitalRepository.getHospitalByHoscode(hospital.getHoscode());
        // 判断targetHospital是否存在
        if(null != targetHospital) {
            // 已存在则对原有数据更新
            hospital.setStatus(targetHospital.getStatus());
            hospital.setCreateTime(targetHospital.getCreateTime());
            hospital.setUpdateTime(new Date());
            hospital.setIsDeleted(0);
            hospitalRepository.save(hospital);
        }else {
            // 不存在则执行添加
            hospital.setStatus(0);
            hospital.setCreateTime(new Date());
            hospital.setUpdateTime(new Date());
            hospital.setIsDeleted(0);
            hospitalRepository.save(hospital);
        }
    }


    // 通过hoscode获取Hospital对象
    @Override
    public Hospital getByHoscode(String hoscode) {
        return hospitalRepository.getHospitalByHoscode(hoscode);
    }


    /**
     * 分页查询医院的数据
     * @param page
     * @param limit
     * @param hospitalQueryVo
     * @return
     */
    @Override
    public Page<Hospital> selectPage(Integer page, Integer limit, HospitalQueryVo hospitalQueryVo){
        Sort sort = Sort.by(Sort.Direction.DESC, "createTime");
        Pageable pageable = PageRequest.of(page-1, limit, sort);
        Hospital hospital = new Hospital();
        BeanUtils.copyProperties(hospitalQueryVo, hospital, Hospital.class);
        // 模糊查询 包含hospital中元素字段信息即可
        ExampleMatcher matcher = ExampleMatcher.matching().withStringMatcher(ExampleMatcher.StringMatcher.CONTAINING).withIgnoreCase(true);
        Example<Hospital> example = Example.of(hospital, matcher);
        Page<Hospital> pages = hospitalRepository.findAll(example, pageable);
        // 循环列表，根据数据字典二次查询封装到page中
        pages.getContent().stream().forEach(item -> {
            // 跨服务调用
            this.packHospital(item);
        });
        return pages;


    }

    /**
     * 根据id与status更新数据
     * @param id
     * @param status
     */
    @Override
    public void updateStatus(String id, Integer status) {
        // 判断status数据是否正常
        if(status == 1 || status == 0) {
            // 根据id获取mongodb中的hospital数据
            Hospital hospital = hospitalRepository.findById(id).get();
            hospital.setStatus(status);
            hospital.setUpdateTime(new Date());
            // 保存hospital
            hospitalRepository.save(hospital);
        }
    }

    /**
     * 根据医院的id查询医院的详细信息，并将医院详细信息以及预定规则封装在map中
     * @param id
     * @return
     */
    @Override
    public Map<String, Object> show(String id) {
        // 查出mongodb中的数据，并根据数据字典查询详细信息
        Hospital hospital = this.packHospital(hospitalRepository.findById(id).get());
        HashMap<String, Object> map = new HashMap<>();
        BookingRule bookingRule = hospital.getBookingRule();
        map.put("bookingRule", bookingRule);
        hospital.setBookingRule(null);
        map.put("hospital", hospital);
        return map;

    }

    /**
     *  根据hoscode获取hosName
     */
    @Override
    public String getHospName(String hoscode) {
        Hospital hospital = hospitalRepository.getHospitalByHoscode(hoscode);
        if (hospital!=null){
            return hospital.getHosname();
        }else{
            return "";
        }

    }

    @Override
    public List<Hospital> findByHosname(String hosname) {
        List<Hospital> hospitalList = hospitalRepository.getHospitalByHosnameLike(hosname);
        return hospitalList;
    }

    @Override
    public Map<String, Object> getHospitalDetail(String hoscode) {
        HashMap<String, Object> hospMap = new HashMap<>();
        Hospital hospital = this.getByHoscode(hoscode);
        BookingRule bookingRule = hospital.getBookingRule();

        hospMap.put("bookingRule", bookingRule);
        hospMap.put("hospital", hospital);
        hospital.setBookingRule(null);
        return hospMap;
    }


    /**
     * 将Date日期（yyyy-MM-dd HH:mm）转换为DateTime
     */
    private DateTime getDateTime(Date date, String timeString) {
        String dateTimeString = new DateTime(date).toString("yyyy-MM-dd") + " "+ timeString;
        DateTime dateTime = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm").parseDateTime(dateTimeString);
        return dateTime;
    }


    /**
     * 封装数据
     * @param hospital
     * @return
     */
    private Hospital packHospital(Hospital hospital) {
        // 只有医院需要通过dict_code与hosttype二者一起才能确定
        String hostypeString = dictFeignClient.getName(DictEnum.HOSTYPE.getDictCode(), hospital.getHostype());
        String provinceString = dictFeignClient.getName(hospital.getProvinceCode());
        String cityString = dictFeignClient.getName(hospital.getCityCode());
        String districtString = dictFeignClient.getName(hospital.getDistrictCode());
        // 向map中填充数据
        hospital.getParam().put("hostypeString", hostypeString);
        hospital.getParam().put("fullAddress", provinceString + cityString + districtString + hospital.getAddress());
        return hospital;
    }





}

